package cn.wanho.handler;

import cn.hutool.core.text.AntPathMatcher;
import cn.wanho.dao.CmsMenuAuthorityMapper;

import cn.wanho.dto.CmsMenuAuthority;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @author qzw
 *
 */
@Component
public class UserFilterInvocationSecurityMetadatasource implements FilterInvocationSecurityMetadataSource {
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Resource
    CmsMenuAuthorityMapper cmsMenuAuthorityMapper;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取请求url的地址
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
       System.out.println(requestUrl);
       int index = requestUrl.indexOf("?");
        String url = null;
        if (index == -1){
            url = requestUrl;
        }else{
            url = requestUrl.substring(0,index);
        }
        //根据路径查询权限
        List<CmsMenuAuthority> cmsMenuAuthorities = cmsMenuAuthorityMapper.selectByUrl(url);
        if (cmsMenuAuthorities == null || cmsMenuAuthorities.size() == 0){
            return null;
        }
       String[] attributes =  new String[cmsMenuAuthorities.size()];
        for (int i = 0; i < cmsMenuAuthorities.size(); i++) {
            attributes[i] = cmsMenuAuthorities.get(i).getAuthorityFlag();
        }
        List<ConfigAttribute> list = SecurityConfig.createList(attributes);
        System.out.println(list);
        return list;
    }


    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
